<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="box-card">
      <el-button type="primary" @click="addVisible = true">添加角色</el-button>

      <el-table :data="rolesData" border style="width: 100%; margin-top: 15px">
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row
              :class="['bdbottom', i1 == 0 ? 'bdtop' : '']"
              v-for="(item1, i1) in scope.row.children"
              :key="item1.id"
            >
              <!-- 渲染一级权限 -->
              <el-col :span="8">
                <el-tag>{{ item1.authName }}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 渲染二级和三级权限 -->
              <el-col :span="16">
                <el-row
                  :class="[i2 == 0 ? '' : 'bdtop']"
                  v-for="(item2, i2) in item1.children"
                  :key="item2.id"
                >
                  <el-col :span="8"
                    ><el-tag type="success">{{ item2.authName }}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="16">
                    <el-tag
                      closable
                      type="warning"
                      v-for="item3 in item2.children"
                      :key="item3.id"
                      @close="item3clear(scope.row, item3.id)"
                    >
                      {{ item3.authName }}
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
            <!-- <pre> {{ scope.row }}</pre> -->
          </template>
        </el-table-column>
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column prop="roleName" label="角色名称"> </el-table-column>
        <el-table-column prop="roleDesc" label="角色描述"> </el-table-column>
        <el-table-column label="操作" width="290px">
          <template slot-scope="scope">
            <!-- 编辑按钮 -->
            <el-button
              type="primary"
              size="mini"
              icon="el-icon-edit"
              @click="showEdit(scope.row.id)"
              >编辑</el-button
            >
            <!-- 删除按钮 -->
            <el-button
              type="danger"
              size="mini"
              icon="el-icon-delete"
              @click="remove(scope.row.id)"
              >删除</el-button
            >
            <!-- 分配角色按钮 -->
            <el-button
              type="warning"
              size="mini"
              icon="el-icon-setting"
              @click="showSetdialog(scope.row)"
              >分配权限</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 编辑弹框 -->
    <el-dialog
      title="提示"
      :visible.sync="EditVisible"
      width="50%"
      @close="editClose"
    >
      <el-form
        :model="editForm"
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
      >
        <el-form-item label="用户名">
          <el-input v-model="editForm.roleId" disabled></el-input>
        </el-form-item>
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="editForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="EditVisible = false">取 消</el-button>
        <el-button type="primary" @click="Editshour">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配权限对话框 -->
    <el-dialog
      title="提示"
      :visible.sync="distributionVisible"
      width="50%"
      @close="clearqx"
    >
      <el-tree
        :data="qxData"
        show-checkbox
        default-expand-all
        node-key="id"
        ref="tree"
        highlight-current
        :props="defaultProps"
        :default-checked-keys="defkeys"
      >
      </el-tree>

      <span slot="footer" class="dialog-footer">
        <el-button @click="distributionVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotrights">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 添加角色弹框 -->
    <el-dialog
      title="提示"
      :visible.sync="addVisible"
      width="50%"
      @close="editClose"
    >
      <el-form
        :model="addForm"
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述">
          <el-input v-model="addForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addVisible = false">取 消</el-button>
        <el-button type="primary" @click="addshour">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      rolesData: [],
      // 编辑框的显示与隐藏
      EditVisible: false,
      // 分配权限的显示与隐藏
      distributionVisible: false,
      // 编辑表单数据
      editForm: {
        roleId: '',
        roleName: '',
        roleDesc: '',
      },
      //表单验证规则
      rules: {
        roleName: [{ required: true, message: '请输入内容', trigger: 'blur' }],
        roleDesc: [{ required: true, message: '请输入内容', trigger: 'blur' }],
      },
      // 用户权限
      qxData: [],
      defaultProps: {
        children: 'children',
        label: 'authName',
      },
      //权限里默认勾选的数组
      defkeys: [],
      // 获取当前点击的id
      roleId: '',
      // 添加用户的弹框的显示和隐藏
      addVisible: false,
      //添加用户的数据
      addForm: {
        roleName: '',
        roleDesc: '',
      },
    }
  },
  mounted() {
    this.getRoleslist()
  },
  methods: {
    async getRoleslist() {
      const { data: res } = await this.$http.get('roles')
      this.rolesData = res.data
    },
    // 删除第三级的标签
    async item3clear(role, rights) {
      const confirmResult = await this.$confirm(
        '此操作将永久删除该标签, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).catch((err) => err)
      if (confirmResult === 'confirm') {
        const { data: res } = await this.$http.delete(
          `roles/${role.id}/rights/${rights}`
        )
        if (res.meta.status !== 200)
          return this.$message.error('用户权限删除失败')
        // 删除成功重新渲染
        this.$message.success(res.meta.msg)
        // this.getRoleslist()  为了防止页面刷新不建议使用这个方法
        // 请求返回的data, 是当前角色下最新的权限数据
        role.children = res.data
      } else {
        this.$message.info('已取消删除')
      }
    },
    // 展示编辑用户
    async showEdit(id) {
      // console.log(id)
      this.EditVisible = true
      const { data: res } = await this.$http.get('roles/' + id)
      if (res.meta.status !== 200) return this.$message.error('获取信息失败！')
      this.editForm = res.data
    },
    // 监听编辑用户对话框的关闭事件
    editClose() {
      this.$refs.ruleForm.resetFields()
    },
    //确认提交编辑
    Editshour() {
      this.$refs.ruleForm.validate(async (valid) => {
        if (!valid) return
        this.EditVisible = false
        const { data: res } = await this.$http.put(
          'roles/' + this.editForm.roleId,
          this.editForm
        )
        if (res.meta.status !== 200)
          return this.$message.error('编辑信息失败！')
        // 成功就渲染
        this.$message.success('修改信息成功！')
        this.getRoleslist()
      })
    },
    // 删除角色
    async remove(id) {
      const confirmResult = await this.$confirm(
        '此操作将永久删除该角色, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).catch((err) => err)
      if (confirmResult === 'confirm') {
        const { data: res } = await this.$http.delete('roles/' + id)
        if (res.meta.status !== 200) return this.$message.error('删除角色失败')
        this.$message.success('删除角色成功！')
        this.getRoleslist()
      } else {
        this.$message.info('已取消删除')
      }
    },
    // 展示分配分配权限对话框
    async showSetdialog(role) {
      this.roleId = role.id
      //获取所有权限的数据
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) return this.$message.error('获取数据失败')
      // 获取到的权限数据
      this.qxData = res.data
      this.getqx(role, this.defkeys)
      this.distributionVisible = true
    },
    // 获取已有的权限
    getqx(node, arr) {
      // 采用递归的方式，获取角色下所有三级权限的id，不保存到defkeys数组里
      //如果当前属性不包括children属性就说明是三级节点
      if (!node.children) {
        return arr.push(node.id)
      }
      node.children.forEach((item) => {
        this.getqx(item, arr)
      })
    },
    // 关闭对话框清空权限
    clearqx() {
      this.defkeys = []
    },
    //分配权限，提交选中的权限,
    async allotrights() {
      const keys = [
        ...this.$refs.tree.getCheckedKeys(),
        ...this.$refs.tree.getHalfCheckedNodes(),
      ]
      // 转化为以逗号隔开的字符串
      const strId = keys.join(',')
      const { data: res } = await this.$http.post(
        `roles/${this.roleId}/rights`,
        {
          rids: strId,
        }
      )
      if (res.meta.status !== 200) return this.$message.error('分配失败')
      this.$message.success('成功分配角色权限')
      this.getRoleslist()
      this.distributionVisible = false
    },
    // 添加新角色
    async addshour() {
      const { data: res } = await this.$http.post('roles', this.addForm)
      if (res.meta.status !== 201) return this.$message.error('创建角色失败')
      this.$message.success('创建成功！')
      this.getRoleslist()
      this.addVisible = false
    },
  },
}
</script>

<style lang="less" scoped>
.el-tag {
  margin: 7px;
}
.bdtop {
  border-top: 1px solid #eee;
}
.bdbottom {
  border-bottom: 1px solid #eee;
}
</style>